package com.ruoyi.phoneController;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.domain.MobilCarInfo;
import com.ruoyi.service.IMobilCarInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 手机端用户车辆Controller
 *
 * @author ruoyi
 * @date 2025-01-20
 */
@RestController
@RequestMapping("/mobile/car")
public class MobilCarInfoController extends BaseController {
    @Autowired
    private IMobilCarInfoService mobilCarInfoService;

    /**
     * 查询用户车辆列表
     */
    @GetMapping("/user/{userId}")
    public AjaxResult getUserCars(@PathVariable Integer userId) {
        List<MobilCarInfo> cars = mobilCarInfoService.selectCarsByUserId(userId);
        return success(cars);
    }

    /**
     * 查询用户默认车辆
     */
    @GetMapping("/user/{userId}/default")
    public AjaxResult getUserDefaultCar(@PathVariable Integer userId) {
        MobilCarInfo defaultCar = mobilCarInfoService.selectDefaultCarByUserId(userId);
        if (defaultCar == null) {
            return error("用户没有默认车辆");
        }
        return success(defaultCar);
    }

    /**
     * 根据ID查询车辆详情
     */
    @GetMapping("/{id}")
    public AjaxResult getCarInfo(@PathVariable Integer id) {
        MobilCarInfo carInfo = mobilCarInfoService.selectMobilCarInfoById(id);
        if (carInfo == null) {
            return error("车辆不存在");
        }
        return success(carInfo);
    }

    /**
     * 新增车辆
     */
    @PostMapping
    public AjaxResult addCar(@RequestBody MobilCarInfo mobilCarInfo) {
        try {
            int result = mobilCarInfoService.insertMobilCarInfo(mobilCarInfo);
            if (result > 0) {
                return success("车辆添加成功");
            } else {
                return error("车辆添加失败");
            }
        } catch (Exception e) {
            logger.error("添加车辆失败", e);
            return error("车辆添加失败：" + e.getMessage());
        }
    }

    /**
     * 修改车辆信息
     */
    @PutMapping
    public AjaxResult updateCar(@RequestBody MobilCarInfo mobilCarInfo) {
        try {
            int result = mobilCarInfoService.updateMobilCarInfo(mobilCarInfo);
            if (result > 0) {
                return success("车辆信息修改成功");
            } else {
                return error("车辆信息修改失败");
            }
        } catch (Exception e) {
            logger.error("修改车辆信息失败", e);
            return error("车辆信息修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除车辆
     */
    @DeleteMapping("/{id}")
    public AjaxResult deleteCar(@PathVariable Integer id) {
        try {
            int result = mobilCarInfoService.deleteMobilCarInfoById(id);
            if (result > 0) {
                return success("车辆删除成功");
            } else {
                return error("车辆删除失败");
            }
        } catch (Exception e) {
            logger.error("删除车辆失败", e);
            return error("车辆删除失败：" + e.getMessage());
        }
    }

    /**
     * 设置默认车辆
     */
    @PostMapping("/set-default")
    public AjaxResult setDefaultCar(@RequestParam Integer userId, @RequestParam Integer carId) {
        try {
            int result = mobilCarInfoService.setDefaultCar(userId, carId);
            if (result > 0) {
                return success("默认车辆设置成功");
            } else {
                return error("默认车辆设置失败");
            }
        } catch (Exception e) {
            logger.error("设置默认车辆失败", e);
            return error("设置默认车辆失败：" + e.getMessage());
        }
    }

    /**
     * 车辆信息验证
     */
    @PostMapping("/validate")
    public AjaxResult validateCarInfo(@RequestBody MobilCarInfo mobilCarInfo) {
        // 基本验证
        if (mobilCarInfo.getType() == null || mobilCarInfo.getType().trim().isEmpty()) {
            return error("车型不能为空");
        }
        
        if (mobilCarInfo.getCarNum() == null || mobilCarInfo.getCarNum().trim().isEmpty()) {
            return error("车牌号不能为空");
        }
        
        // 车牌号格式验证（简单验证）
        String carNum = mobilCarInfo.getCarNum().trim();
        if (carNum.length() < 7 || carNum.length() > 8) {
            return error("车牌号格式不正确");
        }
        
        // 检查是否已存在相同车牌号（同一用户）
        MobilCarInfo queryCarInfo = new MobilCarInfo();
        queryCarInfo.setUid(mobilCarInfo.getUid());
        queryCarInfo.setCarNum(carNum);
        queryCarInfo.setDeleted(0);
        
        List<MobilCarInfo> existingCars = mobilCarInfoService.selectMobilCarInfoList(queryCarInfo);
        if (!existingCars.isEmpty()) {
            // 如果是修改操作，需要排除当前车辆
            if (mobilCarInfo.getId() == null || 
                existingCars.stream().anyMatch(car -> !car.getId().equals(mobilCarInfo.getId()))) {
                return error("该车牌号已存在");
            }
        }
        
        return success("车辆信息验证通过");
    }
}











